package cn.edu.jxau.core.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import cn.edu.jxau.core.controller.ServiceResultConfig;
import cn.edu.jxau.core.domain.Hardware;
import cn.edu.jxau.core.exception.ServiceException;
import cn.edu.jxau.core.util.StringUtil;
import cn.edu.jxau.core.util.mail.Mail;
import cn.edu.jxau.core.util.mail.SendEmail;
import cn.edu.jxau.core.util.mail.sendEmailTest;
import cn.edu.jxau.core.util.upload.FileUpload;
import cn.edu.jxau.framework.dao.core.Session;
import cn.edu.jxau.framework.dao.core.sqlSessionFactory;

public class CheckService extends ServiceSupport{
	//日志信息
    private Logger logger =  LoggerFactory.getLogger(UserService.class);
    
	public CheckService() {
		super();
	}
    public CheckService(String view, Map<String, Object[]> params, Map<String, Object> data) throws ServiceException {
        super(view, params, data);
        execute(view, params, data); // 执行业务
    }
	
	/**
	 *审核申请 
	 *
	 * */
	private void CheckApply(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        
        String applicationID=getParamStringValue(params, "applicationID", 0);
        String reason=getParamStringValue(params, "reason", 0);
        String applyStatus=getParamStringValue(params, "applyStatus", 0);
        String email=getParamStringValue(params, "email", 0);
        String applyType=getParamStringValue(params, "applyType", 0);
        
        param.put("applicationID", applicationID);
        param.put("reason", reason);
        param.put("applyStatus", applyStatus);
        param.put("email", email);
        param.put("applyType", applyType);
        
        Session session=null;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("CheckApply", param, datas);
 
            if(null == applicationID){
            	data.put("result", ServiceResultConfig.FAILED);
            }
            else{
            	//角色申请
            	if("0".equals(applyType)){
            		String roletext="";
            		if("1".equals(applyStatus)){
            			roletext = "恭喜你成功通过了角色申请的审核，望您遵守本网站的相关规定，共创美好的网站环境。 "; // 邮箱内容
            		}else if("0".equals(applyStatus)){
            			roletext = "很遗憾您的角色申请未通过审核。理由是"+reason; // 邮箱内容
            		}
            		
                	String rolesubject = "rolesubject";
                	String rolecontent = "rolecontent"; 
                	sendEmailTest.sendEmail(email, roletext, rolesubject, rolecontent);
            	}
            	//解冻申请
            	else if("1".equals(applyType)){
            		String thawtext="";
            		if("1".equals(applyStatus)){
            			thawtext = "尊敬的用户您好，您的账号已成功解冻 "; // 邮箱内容
            		}else if("0".equals(applyStatus)){
            			thawtext = "很遗憾您申请的解冻账号未通过审核。理由是"+reason; // 邮箱内容
            		}
            		
                	String thawsubject = "thawsubject"; 
                	String thawcontent = "thawcontent"; 
                	sendEmailTest.sendEmail(email, thawtext, thawsubject, thawcontent);
            	}
            	//光谱申请
            	else if("2".equals(applyType)){
            		String spectext="";
            		if("1".equals(applyStatus)){
            			spectext = "尊敬的用户您好，您申请上传到标准库的请求经过专业人员的具体测试，给予通过 "; // 邮箱内容
            		}else if("0".equals(applyStatus)){
            			spectext = "尊敬的用户您好，您申请上传到标准库的请求没有通过专业人员的具体测试。理由是"+reason; // 邮箱内容
            		}
            		// 邮箱内容
                	String specsubject = "specsubject"; 
                	String speccontent = "speccontent"; 
                	sendEmailTest.sendEmail(email, spectext, specsubject, speccontent);
            	}
            	//检验线申请
            	else if("3".equals(applyType)){
            		String linetext="";
            		if("1".equals(applyStatus)){
            			linetext = "尊敬的用户您好，您提交的检验线通过了管理员的审核"; // 邮箱内容
            		}else if("0".equals(applyStatus)){
            			linetext = "尊敬的用户您好，您提交的检验线未通过管理员的审核。理由是"+reason; // 邮箱内容
            		}
                	String linesubject = "linesubject"; 
                	String linecontent = "linecontent"; 
                	sendEmailTest.sendEmail(email, linetext, linesubject, linecontent);
            	}
            	
            	//保存session的数据
            	data.put("session_apply", datas);
                data.put("result", ServiceResultConfig.SUCCESS);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
         
        finally{
        	//释放会话
            session.releaseConnection();
        }
        
	}
	
	/**
	 * 查询所有申请
	 * 
	 * */
	private void listAllApply(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        
        Session session=null;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            session.execute("listAllApply", param, datas);

            
            if(null == datas || datas.isEmpty()){
            	data.put("result", ServiceResultConfig.FAILED);
            }
            else{
            	//保存session的数据
            	data.put("session_apply", datas);
                data.put("result", ServiceResultConfig.SUCCESS);
        		for (Map.Entry<String, Object> entry : data.entrySet()) {  
        		    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
        		  
        		}  
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
        	//释放会话
            session.releaseConnection();
        }
	}
	
	
	/**
	 * 根据id查询
	 * */
	private void listAllApplyById(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 

        String applicationID=getParamStringValue(params, "applicationID", 0);
        
        param.put("applicationID", applicationID);
        
        Session session=null;
        try {
        	session = sqlSessionFactory.getInstance().getSession();
        	session.execute("listAllApplyById", param, datas);
        	
            if(null == datas || datas.isEmpty()){
            	data.put("result", ServiceResultConfig.FAILED);
            }
            else{
            	//保存session的数据
            	data.put("session_apply", datas.get(0));
                data.put("result", ServiceResultConfig.SUCCESS);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
        	//释放会话
            session.releaseConnection();
        }
	}
	
	/**
	 * 根据type查询
	 * 
	 * */
	private void listAllApplyByType(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 

        String applyObjectID=getParamStringValue(params, "applyObjectID", 0);
        int applyType=Integer.parseInt(getParamStringValue(params, "applyType", 0));
        
        param.put("applyObjectID", applyObjectID); // 申请对象ID
        param.put("applyType", applyType); // 申请类型
        
        Session session=null;
        try {
        	session = sqlSessionFactory.getInstance().getSession();
        	//0代表角色申请,1代表解冻申请,2代表光谱申请,3代表检验线申请
        	if(0 == applyType || 1 == applyType ){
        		session.execute("listAllApplyByRole", param, datas);
        	}
        	else if(2 == applyType || 4 == applyType){
        		session.execute("listAllApplyBySpectrum", param, datas);
        	}
        	else if(3 == applyType){
        		session.execute("listAllApplyByLine", param, datas);
        	}
        	
        	
            if(null == datas || datas.isEmpty()){
            	data.put("result", ServiceResultConfig.FAILED);
            }
            else{
            	//保存session的数据
            	data.put("session_apply", datas.get(0));
                data.put("result", ServiceResultConfig.SUCCESS);
            }
                    } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
        	//释放会话
            session.releaseConnection();

        }
	}
	
	/**
	 * 下载申请文件
	 * 
	 * */
	private void downApplyFile(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 

        String fileUrl = getParamStringValue(params, "fileUrl", 0); // 图片路径
        
        String base = FileUpload.getBaseABSPath();
        File file = new File(base,fileUrl);
        data.put("file", file);
        System.out.print(file+"------------");
        if (file.exists()) {
            data.put("result", SUCCESS);
        }else {
            data.put("result", FAILED);
        }

	}
	
	/**
	 * 根据申请类型和审核状态查询需要审核的光谱
	 * @zclong
	 * @2017年9月1日
	 * @ReturnType: void
	 * @param params
	 * @param data
	 */
    private void listApplyByTypeAndStatus(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        List<HashMap<String, Object>> applyObjectDatas = new ArrayList();  // 用来接收数据库返回申请对象信息
        Map<Object, Object> object = new HashMap<Object, Object>(); // 用来接收返回给前台的信息
        List<Object> objectDatas = new ArrayList();  // 用来存储返回给前台数据
        List<String> list;
        List<String> listApply = new ArrayList();
        
        //int applyType=Integer.parseInt(getParamStringValue(params, "applyType", 0)); // 申请类型
        //String applyStatus = getParamStringValue(params, "applyStatus", 0); // 审核状态
        int applyType = 4;
        
        param.put("applyType", applyType); // 申请类型
        //param.put("applyStatus", applyStatus); // 审核状态
        Session session =null;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            //0代表角色申请,1代表解冻申请,2代表光谱申请,3代表检验线申请
            session.execute("listApplyByTypeAndStatus", param, datas);
            
            if(null == datas || datas.isEmpty()){
                data.put("error_msg", "暂无光谱信息！");
                data.put("result", FAILED);
                return;
            } else{
                //保存session的数据
                data.put("applys", datas);
                param.clear();
                int count = 0;
                for (HashMap<String, Object> dataObject : datas) {
                    list = new ArrayList();
                    applyObjectDatas.clear();
                    String applicationID = dataObject.get("applicationID").toString(); // 获取申请表主键ID
                    int applyObjectID = (int) dataObject.get("applyObjectID"); // 获取申请对象ID
                    int userID = (int) dataObject.get("userID"); // 获取申请人ID
                    String applyStatus = dataObject.get("applyStatus").toString(); // 获取审核状态
                    param.put("applyObjectID", applyObjectID);
                    session.execute("listApplySpectrumByID", param, applyObjectDatas);
                    list.add(applyObjectDatas.get(0).get("Id").toString()); // 光谱id
                    list.add((String) applyObjectDatas.get(0).get("spectrumName")); // 光谱名称
                    list.add((String) dataObject.get("applicationTime").toString()); // 申请时间
                    
                    param.clear();
                    applyObjectDatas.clear();
                    param.put("userID", userID);
                    session.execute("queryUserByID", param, applyObjectDatas);

                    list.add((String) applyObjectDatas.get(0).get("name")); // 申请人
                    list.add(applyStatus); // 审核状态
                    list.add(applicationID); // 申请表主键ID
                    objectDatas.add(list);
                }
                data.put("applysDatas", objectDatas);
                data.put("result", ServiceResultConfig.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
        	//释放会话
            session.releaseConnection();
        }
    }
    
    /**
     * 根据申请类型和审核状态查询需要审核的物质
     * @zclong
     * @2017年9月1日
     * @ReturnType: void
     * @param params
     * @param data
     */
    private void queryApplySpectrum(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        List<HashMap<String, Object>> applyObjectDatas = new ArrayList();  // 用来接收数据库返回申请对象信息
        Map<Object, Object> object = new HashMap<Object, Object>(); // 用来接收返回给前台的信息
        List<Object> objectDatas = new ArrayList();  // 用来存储返回给前台数据
        List<String> list;
        List<String> listApply = new ArrayList();
        
        String applicationID = getParamStringValue(params, "applicationID", 0); // 获取申请表主键ID
        
        Session session=null;
        try {
            session = sqlSessionFactory.getInstance().getSession();
            param.put("applicationID", applicationID);
            session.execute("listAllApplyByApplicationID", param, datas);
            if(null == datas || datas.isEmpty()){
                data.put("error_msg", "查询错误！！");
                data.put("result", FAILED);
                return;
            } else{
                int spectrumTypeID = (int) datas.get(0).get("spectrumTypeId"); // 光谱类型编号（获取硬件信息）
                int detectedId = (int) datas.get(0).get("detectedId"); // 被检测物编号（获取被检测物名称）
                String spectrumPicture = (String) datas.get(0).get("spectrumPicture"); // 获取光谱图片
                String reason = (String) datas.get(0).get("reason"); // 审核批注
                int userID = (int) datas.get(0).get("userID"); // 用户编号
                int applyStatus = (int) datas.get(0).get("applyStatus"); // 审核状态
                
                //保存到List数组中
                objectDatas.add(datas.get(0).get("spectrumName")); // 光谱名称
                objectDatas.add(datas.get(0).get("spectrumDescription")); // 光谱描述
                objectDatas.add(datas.get(0).get("applicationTime")); // 申请时间
                objectDatas.add(spectrumPicture); // 获取光谱图片
                objectDatas.add(reason); // 审核批注
                
                datas.clear();
                param.clear();
                param.put("userID", userID);
                session.execute("queryUserByID", param, datas);
                objectDatas.add(datas.get(0).get("name")); // 用户名
                
                datas.clear();
                param.clear();
                param.put("spectrumTypeID", spectrumTypeID);
                session.execute("queryHardwareByspectrumTypeID", param, datas);
                objectDatas.add(datas.get(0).get("hardwareName")); // 硬件设备名称
                
                datas.clear();
                param.clear();
                param.put("detectedId", detectedId);
                session.execute("queryDetected", param, datas);
                objectDatas.add(datas.get(0).get("detectedName")); // 被检测物
                objectDatas.add(applicationID); // 获取申请表主键ID
                objectDatas.add(applyStatus); // 审核状态
                data.put("spectrumInfo", objectDatas);
                data.put("result", SUCCESS);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
        	//释放会话
            session.releaseConnection();
        }
    }
    
    /**
     * 实验员对操作员提交的申请光谱进行审核
     * @zclong
     * @2017年9月1日
     * @ReturnType: void
     * @param params
     * @param data
     */
    private void resolveApplication(Map<String, Object[]> params, Map<String, Object> data){
        Map<String, Object> param = new HashMap<String, Object>(); //用来封装传递给数据库的参数
        List<HashMap<String, Object>> datas = new ArrayList();  // 用来接收数据库返回回来的 
        
        String applicationID = getParamStringValue(params, "applicationID", 0).trim(); // 获取申请表主键ID
        String passStatus = getParamStringValue(params, "passStatus", 0); // 审核通过true
        String refuseStatus = getParamStringValue(params, "refuseStatus", 0); // 审核通过true
        String content = getParamStringValue(params, "content", 0); // 审核理由
        String refusecontent = getParamStringValue(params, "refusecontent", 0); // 拒绝审核理由
        String msg = "";
        
        if(StringUtil.isEmpty(applicationID) && StringUtil.isEmpty(passStatus) && StringUtil.isEmpty(refuseStatus) && StringUtil.isEmpty(content) && StringUtil.isEmpty(refusecontent)) {
            data.put("error_msg", "请重新审核");
            data.put("result", FAILED);
            return;
        }else {
            Session session =null;
            try {
                session = sqlSessionFactory.getInstance().getSession();
                param.put("applicationID", applicationID);
                if(("true").equals(passStatus)) {
                    param.put("passStatus", 2); // 通过审核
                    param.put("content", content); // 审核理由
                    msg = content;
                }else if(("true").equals(refuseStatus)) {
                    param.put("passStatus", 0); // 拒绝审核
                    param.put("content", refusecontent); // 审核理由
                    msg = refusecontent;
                }
                boolean flag = session.execute("modifyStatus", param, datas);
                if(flag != true) {
                    data.put("error_msg", "操作失败，请重新审核");
                    data.put("result", FAILED);
                    return;
                }else {
                    param.clear();
                    param.put("applicationID", applicationID);
                    session.execute("queryUserByApplicationID", param, datas);
                    String email = (String) datas.get(0).get("email");
                    // 邮件模板
                    SendEmail.init(null); //进行初始化,设置邮箱配置文件的路径，如果为空，默认为email_template.properties在类路径下
                    String applysubject = SendEmail.getSubject("applysubject");//对应配置文件中的subject
                    String applycontent = SendEmail.getContent("applycontent", msg);//对应配置文件中的content
                    Mail mail = SendEmail.getMail(email, applysubject, applycontent);
                    SendEmail.sendMail(mail);
                    data.put("result", SUCCESS);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally{
            	//释放会话
                session.releaseConnection();
            }
        }
    }
}

